package main
import "github.com/go-martini/martini"
import (
	"github.com/martini-contrib/encoder"
	"github.com/martini-contrib/cors"
	"strconv"
	"net/http"
	"hotel_Manager_Api/model/dbEngin"
	"hotel_Manager_Api/util"
	"hotel_Manager_Api/webConfig"
)

func main() {
	m := newMartini()
	webConfig.RouteConfig(m)
	addr := util.Config().MustValue("web","addr",":3000")
	m.RunOnAddr(addr)
}

func newMartini() *martini.ClassicMartini  {
	m := martini.Classic()
	m.Use(func(c martini.Context, w http.ResponseWriter, r *http.Request) {
		c.Map(util.SnowFlakeNodeEntity)
	})
	m.Use(func(c martini.Context, w http.ResponseWriter, r *http.Request) {
		// Use indentations. &pretty=1
		pretty, _ := strconv.ParseBool(r.FormValue("pretty"))
		// Use null instead of empty object for json &null=1
		null, _ := strconv.ParseBool(r.FormValue("null"))
		// Some content negotiation
		switch r.Header.Get("Content-Type") {
		case "application/xml":
			c.MapTo(encoder.XmlEncoder{PrettyPrint: pretty}, (*encoder.Encoder)(nil))
			w.Header().Set("Content-Type", "application/xml; charset=utf-8")
		default:
			c.MapTo(encoder.JsonEncoder{PrettyPrint: pretty, PrintNull: null}, (*encoder.Encoder)(nil))
			w.Header().Set("Content-Type", "application/json; charset=utf-8")
		}
	})

	m.Use(cors.Allow(&cors.Options{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"PUT", "GET","POST","DELETE"},
		AllowHeaders:     []string{"Origin", "X-Requested-With", "Content-Type", "Accept","Authorization"},
		ExposeHeaders:    []string{"*"},
		AllowCredentials: true,
	}))
	m.Map(dbEngin.GetEnging())
	return m
}
